#include "RemoteServer.h"
#include <iostream>
#include "Application.h"
#include "KeyboardController.h"


cat::RemoteServer::RemoteServer(std::string adress, int port)
	: _serverPort(port),
	_serverAdress(adress)
{
	std::cout << "Recovering server information... ";
	_socket.setBlocking(true);
	sf::Socket::Status status = _socket.connect(_serverAdress, _serverPort);
	if (status != sf::Socket::Done)
	{
		std::cerr<<"Failed"<<std::endl;
	}

	std::cout << "Done" <<std::endl;
}


cat::RemoteServer::~RemoteServer(void)
{
}

void cat::RemoteServer::think(void)
{
	cat::Application& application = cat::Application::current();
	cat::ControllerBase* controller = NULL;
	while ((controller = application.popControllerRequieringSynchronization()) != NULL)
	{
		cat::Tank& tank = controller->getTank();
		sf::Packet packet;
		packet //<< "update" 
			<< tank.getPosition().x 
			<< tank.getPosition().y
			<< tank.getVelocity().x
			<< tank.getVelocity().y
			<< controller->getControlPosition().x
			<< controller->getControlPosition().y;
		std::cout 
			<< "sent location: ("<< tank.getPosition().x << "," << tank.getPosition().y << ")" << std::endl 
			<< "sent velocity: (" << tank.getVelocity().x << "," << tank.getVelocity().y << ")" << std::endl << std::endl;
		_socket.send(packet);
	}
}

void cat::RemoteServer::connect()
{
	cat::Application& application = cat::Application::current();

	cat::Tank* tank = new cat::Tank();
	cat::ControllerBase* playerController = new cat::KeyboardController(*tank);
	application.registerTank(tank);
	application.registerController(playerController);
}

void cat::RemoteServer::disconnect(void)
{
	
}